//
//  XHRTabBar.m
//  BuDeJie
//
//  Created by haoran on 16/4/1.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRTabBar.h"
@interface XHRTabBar ()

/** 加号按钮 **/
@property (nonatomic, weak) UIButton * plusBtn;

/** 上一次选中的tabbar按钮 **/
@property (nonatomic, weak) UIControl *previousClickedTabBarButton;
@end

@implementation XHRTabBar


#pragma mark ---- 懒加载加号按钮
-(UIButton *)plusBtn{
    if (_plusBtn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //设置图片
        [btn setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateSelected];
        
        //根据内容匹配尺寸
        [btn sizeToFit];
        
        _plusBtn = btn;
        
        [self addSubview:btn];
    }
    return _plusBtn;
}

#pragma mark ---- 布局子控件
-(void)layoutSubviews{
    [super layoutSubviews];
//    NSLog(@"%@",self.subviews);
    //调整子控件布局
    // self.items 保存的是tabbarItem模型
    NSInteger count = self.items.count + 1 ; //加1是为了考虑发布按钮

    
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    CGFloat btnW = self.xhr_width/ count;
    CGFloat btnH = self.xhr_height;
    //遍历子控件  UITabBarButton 是苹果的私有类
    int i = 0;
    for (UIControl * tabBarButton in self.subviews) {
                   
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            if(i == 0 && self.previousClickedTabBarButton == nil){ //刚开始最前面的tabbarButton
                self.previousClickedTabBarButton = tabBarButton;
            }
            
            
            if (i == 2) { //跳过加号按钮
                i++;
            }
            
            btnX = i * btnW;
            //设置frame
            tabBarButton.frame = CGRectMake(btnX, btnY, btnW, btnH);
            i++;
            
            // 添加tabbar按钮点击事件
            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    // 设置加号按钮居中
    //    self.plusButton.center = self.center; 不能设置center.
    // 不能使用_plusBtn,否则不会调用get方法去懒加载
    self.plusBtn.center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    
}

// tabBar 按钮点击事件
-(void)tabBarButtonClick: (UIControl *)tabBarButton{

    // 告诉外界,tabbarButton被重复点击了
    if (self.previousClickedTabBarButton == tabBarButton) {
        XHRLog(@"发通知说被重复点击");
        [[NSNotificationCenter defaultCenter] postNotificationName:XHRTabBarButtonDidRepeatClickNotification object:nil];
        
        
    }
    
    self.previousClickedTabBarButton = tabBarButton;

}


@end
